package com.zdlee.netty.server9.server;

import com.zdlee.netty.server9.command.LoginRequestPacket;
import com.zdlee.netty.server9.command.Packet;
import com.zdlee.netty.server9.command.PacketCodeC;
import com.zdlee.netty.server9.response.LoginResponsePacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

/**
 * @author zdlee
 * @description: ${DESCRIPTION}
 * @create 2018-11-29 13:53
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(new Date() + ": 客户端开始登录……");
        ByteBuf buf= (ByteBuf) msg;

        Packet packet= PacketCodeC.INSTANCE.decode(buf);
        if(packet instanceof LoginRequestPacket){
            LoginRequestPacket loginRequestPacket= (LoginRequestPacket) packet;

            LoginResponsePacket loginResponsePacket=new LoginResponsePacket();
            loginResponsePacket.setVersion(packet.getVersion());
            if(valid(loginRequestPacket))
            {
                loginResponsePacket.setSuccess(true);
                System.out.println(new Date() + ": 登录成功!");
            }else
            {
                loginResponsePacket.setReason("账号密码校验失败");
                loginResponsePacket.setSuccess(false);
                System.out.println(new Date()+":登录失败!");
            }
            //登录响应
            ByteBuf responseByteBuf=PacketCodeC.INSTANCE.encode(ctx.alloc(),loginResponsePacket);
            ctx.channel().writeAndFlush(responseByteBuf);
        }

    }

    private boolean valid(LoginRequestPacket loginRequestPacket){
        return true;
    }


}
